package searchtab.highlight;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;

public class MarkerHighlighter {

    private IAnnotationModel annotationModel;

    private static Annotation[] fOccurrenceAnnotations = new Annotation[0];

    public MarkerHighlighter(IAnnotationModel annotationModel) {
        this.annotationModel = annotationModel;
    }

    public void addHighlights(final ArrayList<Position> positions) {
        if (positions == null) {
            return;
        }

        new Job("SearchTab mark job") {

            @Override
            public IStatus run(IProgressMonitor arg0) {
                Map<Annotation, Position> annotationMap = new HashMap<Annotation, Position>(
                        (int) (positions.size() * 1.33));

                for (int i = 0; i < positions.size(); i++) {
                    annotationMap.put(new Annotation("SearchTab.defaultMarker", false, null), positions.get(i));
                }

                if (annotationModel instanceof IAnnotationModelExtension) {
                    ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations,
                            annotationMap);
                } else {
                    Map.Entry mapEntry;
                    for (Iterator iter = annotationMap.entrySet().iterator(); iter.hasNext(); annotationModel
                            .addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue())) {
                        mapEntry = (java.util.Map.Entry) iter.next();
                    }

                }
                fOccurrenceAnnotations = annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);

                return Status.OK_STATUS;

            }

        }.run(new NullProgressMonitor());

    }

    public void removeAll() {
        if (annotationModel instanceof IAnnotationModelExtension) {
            ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations,
                    new HashMap<Annotation, Position>());
        } else {
            for (Annotation annotation : fOccurrenceAnnotations) {
                annotationModel.removeAnnotation(annotation);
            }

        }

    }
}